package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.User;
import com.cskaoyan.mall.service.admin.UserService;
import com.cskaoyan.mall.service.admin.UserServiceImpl;
import com.cskaoyan.mall.utils.StringUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//"id","email","nickname","pwd","recipient","address","phone"}
@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {
    private Gson gson = new Gson();
    private UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/","");
        if ("allUser".equals(action)) {
            allUser(request,response);
        }else if ("searchUser".equals(action)) {
            searchUser(request,response);
        }else if ("deleteUser".equals(action)) {
            deleteUser(request,response);
        }
    }

    /**
     * 删除指定的id的用户数据
     * @param request
     * @param response
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        //如果什么都没有输入，那么直接返回message并显示
        int code = userService.deleteUser(id);
        if (code == 200) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除失败")));
    }

    /**
     * 模糊查询用户账号
     * @param request
     * @param response
     */
    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        //如果什么都没有输入，那么直接返回message并显示
        if (StringUtils.isEmpty(word)) {
            response.getWriter().println(gson.toJson(Result.error("输入的参数不能为空")));
            return;
        }
        List<User> users = userService.searchUser(word);
        response.getWriter().println(gson.toJson(Result.ok(users)));
    }

    /**
     * 显示全部的用户
     * @param request
     * @param response
     */
    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> userList = userService.allUser();
        response.getWriter().println(gson.toJson(Result.ok(userList)));
    }

}
